using System.Linq;
using Kiwi.Container.Application;
using Kiwi.Container.DependencyInjection;

namespace Kiwi.Container.Web
{
    public static class ContainerBuilderExtensions
    {
        public static IContainerBuilder EnablePerHttpRequestContainers(this IContainerBuilder builder)
        {
            if (!builder.Extensions.Any(a => a is IHttpRequestContainerActivator))
            {
                builder.Extensions.Add(HttpRequestContainerActivator.Default);
            }
            return builder;
        }

        public static IContainerBuilder EnablePerHttpSessionContainers(this IContainerBuilder builder)
        {
            if (!builder.Extensions.Any(a => a is IHttpSessionContainerActivator))
            {
                var requestActivatorIndex = builder.Extensions.FindIndex(a => a is IHttpRequestContainerActivator);
                if (requestActivatorIndex < 0)
                {
                    builder.Extensions.Add(HttpSessionContainerActivator.Default);
                }
                else
                {
                    builder.Extensions.Insert(requestActivatorIndex, HttpSessionContainerActivator.Default);
                }
            }
            return builder;
        }

        public static IContainerBuilder EnableHttpHandlerDependencyInjection(
            this IContainerBuilder builder, IEnumerateDependentProperties dependentProperties, bool applyToControls)
        {
            if (!builder.Extensions.Any(a => a is IHttpHandlerDependencyInjector))
            {
                builder.Extensions.Add(new HttpHandlerDependencyInjector {DependentProperties = dependentProperties, ApplyToControls = applyToControls});
            }
            return builder;
        }
    }
}